<template>
  <Drawer
      v-model="visible"
      title="用户信息编辑"
      width="450"
      :mask-closable="false"
      :styles="$PnUtil.buildDrawerStyleByHasFooter()">
    <Form ref="form" :label-width="105" :model="formData" :rules="ruleValidate">
      <FormItem label="id" prop="id" hidden>
        <Input v-model="formData.id"/>
      </FormItem>
      <FormItem label="账号" prop="username">
        <Input v-model="formData.username" :disabled="formData.id != ''"/>
      </FormItem>
      <FormItem label="密码" prop="password">
        <Input v-model="formData.password" type="password" :disabled="formData.id != ''"/>
      </FormItem>
      <FormItem label="角色" prop="role_id">
        <RadioGroup v-model="formData.role_id" type="button">
          <Radio label="2" border>普通用户</Radio>
          <Radio label="1" border>管理员</Radio>
        </RadioGroup>
      </FormItem>
    </Form>

    <DrawerFooter>
      <Button class="m-r-5px" @click="visible = false">关闭</Button>
      <Button type="primary" @click="submitForm" :loading="loading">保存</Button>
    </DrawerFooter>
  </Drawer>
</template>

<script>
import ManageMixin from "@/mixin/ManageMixin";

export default {
  name: "UserForm",
  mixins: [ManageMixin],
  data() {
    return {
      visible: false,
      loading: false,
      formData: {
        id: '',
        role_id: '2',
        username: '',
        password: '',
        status: '1',
        email: '',
        qq: '',
        profession: ''
      },

      ruleValidate: {
        username: [
          {required: true, message: '账号不能为空', trigger: 'blur'},
          {min: 3, max: 16, message: '账号长度3-16个字符', trigger: 'blur'}
        ],
        password: [
          {required: true, message: '密码不能为空', trigger: 'blur'},
          {type: 'string', min: 3, max: 16, message: '密码长度3-16个字符', trigger: 'blur'}
        ]
      }
    }
  },
  mounted() {

  },
  methods: {
    init(type, id) {
      this.visible = true
      this.$nextTick(() => {
        this.$refs.form.resetFields()
        if (type == 'edit') {
          this.$PnApi.UserApi.getUserById(id).then(result => {
            this.formData = this.recover(this.formData, result.data.payload)
          })
        }
      })
    },

    submitForm() {
      let saveUser = () => {
        this.loading = true
        this.$PnApi.UserApi.saveUser(this.formData).then(result => {
          if (result.data.success) {
            this.visible = false
            this.$Message.success(result.data.message)
            this.$emit("refreshDataList")
          } else {
            this.$Message.error(result.data.message)
          }
          this.loading = false
        })
      }
      if (this.formData.id) {
        saveUser()
      }else {
        this.$refs.form.validate((valid) => {
          if (valid) {
            saveUser()
          }
        });
      }
    }
  },
  computed: {}
}
</script>

<style lang="less" scoped>

</style>
